/**
 * 注册页面
 */
import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  Card,
  Typography,
  Row,
  Col,
  Steps,
  Alert,
  Progress
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  PhoneOutlined,
  TeamOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { useAuth } from '../contexts/AuthContext';
import { useTheme } from '../contexts/ThemeContext';
import { RegisterRequest, PasswordStrength } from '../types/auth';
import { showNotification } from '../utils/notification';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

const Register: React.FC = () => {
  const navigate = useNavigate();
  const { register, state } = useAuth();
  const { currentTheme } = useTheme();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [passwordStrength, setPasswordStrength] = useState<PasswordStrength | null>(null);

  // 使用状态保存表单数据
  const [formData, setFormData] = useState<Partial<RegisterRequest>>({
    role_ids: []
  });

  // 初始化表单数据
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [form, formData]);

  /**
   * 检查密码强度
   */
  const checkPasswordStrength = (password: string): PasswordStrength => {
    const requirements = {
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      digit: /\d/.test(password),
      special: /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password)
    };

    const score = Object.values(requirements).filter(Boolean).length;
    const feedback: string[] = [];

    if (!requirements.length) feedback.push('密码长度至少8个字符');
    if (!requirements.uppercase) feedback.push('包含至少一个大写字母');
    if (!requirements.lowercase) feedback.push('包含至少一个小写字母');
    if (!requirements.digit) feedback.push('包含至少一个数字');
    if (!requirements.special) feedback.push('包含至少一个特殊字符');

    let strength: 'weak' | 'medium' | 'strong' | 'very_strong';
    if (score <= 2) strength = 'weak';
    else if (score <= 3) strength = 'medium';
    else if (score <= 4) strength = 'strong';
    else strength = 'very_strong';

    return {
      is_valid: score === 5,
      score,
      strength,
      feedback,
      requirements
    };
  };

  /**
   * 处理注册提交
   */
  const handleSubmit = async (values: RegisterRequest) => {
    // 只有在最后一步才允许提交
    if (currentStep !== 2) {
      console.log('不在最后一步，阻止提交');
      return;
    }

    setLoading(true);

    try {
      // 使用保存的状态数据
      console.log('当前保存的表单数据:', formData);

      // 确保包含role_ids字段
      const registerData = {
        ...formData,
        role_ids: formData.role_ids || []
      };

      console.log('提交注册数据:', registerData);

      // 验证必需字段
      const requiredFields = ['username', 'email', 'password', 'confirm_password'];
      const missingFields = requiredFields.filter(field => !registerData[field]);

      if (missingFields.length > 0) {
        console.error('缺少必需字段:', missingFields);
        showNotification('error', '表单数据不完整', `缺少字段: ${missingFields.join(', ')}`);
        return;
      }

      await register(registerData as RegisterRequest);
      showNotification('success', '注册成功', '请联系管理员激活您的账户');
      navigate('/login');
    } catch (error: any) {
      console.error('注册失败:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 下一步
   */
  const nextStep = async () => {
    try {
      if (currentStep === 0) {
        await form.validateFields(['username', 'email', 'password', 'confirm_password']);
        // 保存第一步数据
        const step1Data = form.getFieldsValue(['username', 'email', 'password', 'confirm_password']);
        setFormData(prev => ({ ...prev, ...step1Data }));
        console.log('第1步数据已保存:', step1Data);
      } else if (currentStep === 1) {
        await form.validateFields(['full_name', 'phone', 'department', 'position']);
        // 保存第二步数据
        const step2Data = form.getFieldsValue(['full_name', 'phone', 'department', 'position']);
        setFormData(prev => ({ ...prev, ...step2Data }));
        console.log('第2步数据已保存:', step2Data);
      }

      setCurrentStep(currentStep + 1);
    } catch (error) {
      console.log('验证失败:', error);
    }
  };

  /**
   * 上一步
   */
  const prevStep = () => {
    setCurrentStep(currentStep - 1);
    // 恢复表单数据
    form.setFieldsValue(formData);
  };

  const registerStyles = {
    container: {
      minHeight: '100vh',
      background: currentTheme.isDark 
        ? 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)'
        : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '20px',
    },
    card: {
      background: currentTheme.isDark 
        ? 'rgba(30, 30, 30, 0.9)'
        : 'rgba(255, 255, 255, 0.95)',
      backdropFilter: 'blur(10px)',
      border: currentTheme.isDark 
        ? '1px solid rgba(255, 255, 255, 0.1)'
        : '1px solid rgba(255, 255, 255, 0.2)',
      borderRadius: '16px',
      boxShadow: currentTheme.isDark
        ? '0 8px 32px rgba(0, 0, 0, 0.3)'
        : '0 8px 32px rgba(0, 0, 0, 0.1)',
    },
    header: {
      textAlign: 'center' as const,
      marginBottom: '32px',
    },
    title: {
      margin: '0 0 8px 0',
      color: currentTheme.isDark ? '#fff' : '#1a1a1a',
      fontSize: '28px',
      fontWeight: 600,
    },
    subtitle: {
      margin: 0,
      color: currentTheme.isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)',
      fontSize: '14px',
    },
  };

  const getPasswordStrengthColor = (strength: string) => {
    switch (strength) {
      case 'weak': return '#ff4d4f';
      case 'medium': return '#faad14';
      case 'strong': return '#52c41a';
      case 'very_strong': return '#1890ff';
      default: return '#d9d9d9';
    }
  };

  const steps = [
    {
      title: '账户信息',
      icon: <UserOutlined />,
    },
    {
      title: '个人信息',
      icon: <TeamOutlined />,
    },
    {
      title: '完成注册',
      icon: <CheckCircleOutlined />,
    },
  ];

  return (
    <div style={registerStyles.container}>
      <Row justify="center" align="middle" style={{ minHeight: '100vh' }}>
        <Col xs={22} sm={20} md={16} lg={12} xl={8}>
          <Card style={registerStyles.card} bordered={false}>
            {/* 系统标题 */}
            <div style={registerStyles.header}>
              <Title level={2} style={registerStyles.title}>
                注册 DataPlexus
              </Title>
              <Paragraph style={registerStyles.subtitle}>
                创建您的数据治理平台账户
              </Paragraph>
            </div>

            {/* 步骤指示器 */}
            <Steps current={currentStep} style={{ marginBottom: 32 }}>
              {steps.map((step, index) => (
                <Step key={index} title={step.title} icon={step.icon} />
              ))}
            </Steps>

            {/* 错误提示 */}
            {state.error && (
              <Alert
                message="注册失败"
                description={state.error}
                type="error"
                showIcon
                closable
                style={{ marginBottom: 24 }}
              />
            )}

            {/* 注册表单 */}
            <Form
              form={form}
              name="register"
              onFinish={handleSubmit}
              autoComplete="off"
              size="large"
              layout="vertical"
              onKeyDown={(e) => {
                // 防止在前面步骤中按回车键提交表单
                if (e.key === 'Enter' && currentStep !== 2) {
                  e.preventDefault();
                }
              }}
            >
              {/* 第一步：账户信息 */}
              {currentStep === 0 && (
                <>
                  <Form.Item
                    name="username"
                    label="用户名"
                    rules={[
                      { required: true, message: '请输入用户名' },
                      { min: 3, max: 50, message: '用户名长度为3-50个字符' },
                      { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和连字符' }
                    ]}
                  >
                    <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
                  </Form.Item>

                  <Form.Item
                    name="email"
                    label="邮箱地址"
                    rules={[
                      { required: true, message: '请输入邮箱地址' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input prefix={<MailOutlined />} placeholder="请输入邮箱地址" />
                  </Form.Item>

                  <Form.Item
                    name="password"
                    label="密码"
                    rules={[
                      { required: true, message: '请输入密码' },
                      { min: 8, message: '密码至少8个字符' },
                      {
                        validator: (_, value) => {
                          if (value) {
                            const strength = checkPasswordStrength(value);
                            setPasswordStrength(strength);
                            if (!strength.is_valid) {
                              return Promise.reject(new Error('密码强度不足'));
                            }
                          }
                          return Promise.resolve();
                        }
                      }
                    ]}
                  >
                    <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
                  </Form.Item>

                  {/* 密码强度指示器 */}
                  {passwordStrength && (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ marginBottom: 8 }}>
                        <Text>密码强度: </Text>
                        <Text style={{ color: getPasswordStrengthColor(passwordStrength.strength) }}>
                          {passwordStrength.strength === 'weak' && '弱'}
                          {passwordStrength.strength === 'medium' && '中等'}
                          {passwordStrength.strength === 'strong' && '强'}
                          {passwordStrength.strength === 'very_strong' && '很强'}
                        </Text>
                      </div>
                      <Progress
                        percent={(passwordStrength.score / 5) * 100}
                        strokeColor={getPasswordStrengthColor(passwordStrength.strength)}
                        showInfo={false}
                        size="small"
                      />
                      {passwordStrength.feedback.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            密码要求: {passwordStrength.feedback.join('、')}
                          </Text>
                        </div>
                      )}
                    </div>
                  )}

                  <Form.Item
                    name="confirm_password"
                    label="确认密码"
                    dependencies={['password']}
                    rules={[
                      { required: true, message: '请确认密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('password') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                  >
                    <Input.Password prefix={<LockOutlined />} placeholder="请再次输入密码" />
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" onClick={nextStep} block>
                      下一步
                    </Button>
                  </Form.Item>
                </>
              )}

              {/* 第二步：个人信息 */}
              {currentStep === 1 && (
                <>
                  <Form.Item
                    name="full_name"
                    label="真实姓名"
                  >
                    <Input prefix={<UserOutlined />} placeholder="请输入真实姓名" />
                  </Form.Item>

                  <Form.Item
                    name="phone"
                    label="手机号码"
                  >
                    <Input prefix={<PhoneOutlined />} placeholder="请输入手机号码" />
                  </Form.Item>

                  <Form.Item
                    name="department"
                    label="部门"
                  >
                    <Input placeholder="请输入部门" />
                  </Form.Item>

                  <Form.Item
                    name="position"
                    label="职位"
                  >
                    <Input placeholder="请输入职位" />
                  </Form.Item>

                  <Form.Item>
                    <Row gutter={16}>
                      <Col span={12}>
                        <Button onClick={prevStep} block>
                          上一步
                        </Button>
                      </Col>
                      <Col span={12}>
                        <Button type="primary" onClick={nextStep} block>
                          下一步
                        </Button>
                      </Col>
                    </Row>
                  </Form.Item>
                </>
              )}

              {/* 第三步：确认注册 */}
              {currentStep === 2 && (
                <>
                  <Alert
                    message="注册须知"
                    description="账户创建后需要管理员激活才能正常使用。请确认信息无误后提交注册申请。"
                    type="info"
                    showIcon
                    style={{ marginBottom: 24 }}
                  />

                  <Form.Item>
                    <Row gutter={16}>
                      <Col span={12}>
                        <Button onClick={prevStep} block>
                          上一步
                        </Button>
                      </Col>
                      <Col span={12}>
                        <Button
                          type="primary"
                          htmlType="submit"
                          loading={loading || state.loading}
                          block
                        >
                          提交注册
                        </Button>
                      </Col>
                    </Row>
                  </Form.Item>
                </>
              )}
            </Form>

            {/* 登录链接 */}
            <div style={{ textAlign: 'center', marginTop: 24 }}>
              <Text type="secondary">
                已有账户？
                <Link to="/login" style={{ marginLeft: 8 }}>
                  立即登录
                </Link>
              </Text>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Register;
